package com.laowang.project.system.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.laowang.common.utils.SecurityUtils;
import com.laowang.project.system.domain.*;
import com.laowang.project.system.mapper.SysRoleMapper;
import com.laowang.project.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.laowang.framework.aspectj.lang.annotation.Log;
import com.laowang.framework.aspectj.lang.enums.BusinessType;

import org.springframework.web.bind.annotation.*;
import com.laowang.framework.web.controller.BaseController;
import com.laowang.framework.web.domain.AjaxResult;
import com.laowang.common.utils.poi.ExcelUtil;
import com.laowang.framework.web.page.TableDataInfo;
import oshi.jna.platform.mac.SystemB;

/**
 * 票种Controller
 *
 * @author laowang
 * @date 2023-06-21
 */
@Api(tags = "票种接口")
@RestController
@RequestMapping("/ticket")
public class MyCyhTicketController extends BaseController {
    @Autowired
    private MyCyhTicketService myCyhTicketService;

    @Autowired
    private MyCyhActivityService myCyhActivityService;

    @Autowired
    private MyCyhVipAuthorityService myCyhVipAuthorityService;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private MyCyhVipService myCyhVipService;

    /**
     * 查询票种列表
     */
    @ApiOperation(value = "小程序端 根据活动id查询票种列表",notes = "")
    @GetMapping("/web/{id}")
    public AjaxResult webId(@PathVariable("id") Integer id) {
        List<MyCyhTicket> list =   myCyhTicketService.selectMyCyhTicketListwebId(id);
        MyCyhActivity myCyhActivity = myCyhActivityService.selectMyCyhActivityById(id);

        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        WxUser wxUser = wxUserService.selectWxUserById(mid);
        Integer discountType = myCyhActivity.getDiscountType();
        if (discountType !=null){
            if (discountType == 1){
                // `discount_type` int DEFAULT NULL COMMENT '1固定会员折扣,2会员等级折扣',
                if (wxUser.getVipLevel() != null && wxUser.getExpireTime() !=null && wxUser.getExpireTime().after(new Date())){
                    BigDecimal fixDisPrice = myCyhActivity.getFixDisPrice();
                    if (fixDisPrice !=null){
                        for (MyCyhTicket myCyhTicket : list) {
                            Integer isUse = myCyhTicket.getIsUse();
                            if (isUse != 1){
                                // 不用邀请码
                                BigDecimal price = myCyhTicket.getPrice();
                                if (price.compareTo(fixDisPrice)>0){
                                    BigDecimal disprice = price.subtract(fixDisPrice);
                                    myCyhTicket.setPrice1(disprice);
                                }
                            }
                        }
                    }
                }



            }else if (discountType == 2){


                if (wxUser.getVipLevel() != null && wxUser.getExpireTime() !=null && wxUser.getExpireTime().after(new Date())){
                    /*MyCyhVipAuthority myCyhVipAuthority = new MyCyhVipAuthority();
                    myCyhVipAuthority.setAuthorityId(2);
                    myCyhVipAuthority.setVipLevel(wxUser.getVipLevel());
                    List<MyCyhVipAuthority> myCyhVipAuthorities = myCyhVipAuthorityService.selectMyCyhVipAuthorityList(myCyhVipAuthority);
                    if (myCyhVipAuthorities.size()>0){
                        MyCyhVipAuthority myCyhVipAuthority1 = myCyhVipAuthorities.get(0);
                        for (MyCyhTicket myCyhTicket : list) {
                            Integer isUse = myCyhTicket.getIsUse();
                            if (isUse != 1){
                                // 不用邀请码
                                BigDecimal price = myCyhTicket.getPrice();
                                if (myCyhVipAuthority1.getDiscount() !=null && myCyhVipAuthority1.getDiscount().compareTo(new BigDecimal(0))>0){
                                    BigDecimal price1 = price.multiply(myCyhVipAuthority1.getDiscount()).divide(new BigDecimal(100));
                                    myCyhTicket.setPrice1(price1);
                                }


                            }
                        }
                    }*/

                    MyCyhVip myCyhVip = myCyhVipService.selectMyCyhVipByLevel(wxUser.getVipLevel());
                    BigDecimal actDiscount = myCyhVip.getActDiscount();
                    for (MyCyhTicket myCyhTicket : list) {
                        Integer isUse = myCyhTicket.getIsUse();
                        if (isUse != 1){
                            // 不用邀请码
                            BigDecimal price = myCyhTicket.getPrice();
                            if (actDiscount !=null && actDiscount.compareTo(new BigDecimal(0) )>0){
                                BigDecimal price1 = price.multiply(new BigDecimal(100).subtract(actDiscount)).divide(new BigDecimal(100));
                                myCyhTicket.setPrice1(price1);
                            }

                        }
                    }
                }

            }
        }

        return AjaxResult.success("操作成功",list);
    }


    /**
     * 查询票种列表
     */
    @ApiOperation(value = "查询票种列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:ticket:list')")
    @GetMapping("/list")
        public TableDataInfo list(MyCyhTicket myCyhTicket) {

        List<MyCyhActivity> myCyhActivities = myCyhActivityService.selectMyCyhActivityListWeb(null);
        Map<Integer, String> collect = myCyhActivities.stream().collect(Collectors.toMap(MyCyhActivity::getId, MyCyhActivity::getTitle));

        List<MyCyhTicket> list = new ArrayList<>();
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        //不是管理员
        if (!userId.equals(1L)  ) {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(userId);
            // 是 活动管理者
            Boolean b = sysRoles.stream().anyMatch(sysRole -> sysRole.getRoleKey().equals("activityManager"));
            if (b) {
                List<Integer> listIds = myCyhActivityService.selectActivityIdByCreateBy(userId);
                if (listIds.size()>0){
                    myCyhTicket.setListIds(listIds);
                    list =  myCyhTicketService.selectMyCyhTicketListByActivityId(myCyhTicket);
                }

            }else {
                startPage();
                list = myCyhTicketService.selectMyCyhTicketList(myCyhTicket);
            }

        }else {
            //管理员
            startPage();
            list = myCyhTicketService.selectMyCyhTicketList(myCyhTicket);
        }


        for (MyCyhTicket cyhTicket : list) {
            if (collect.containsKey(cyhTicket.getActivityId())){
                cyhTicket.setActivityName(collect.get(cyhTicket.getActivityId()));
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出票种列表
     */
    @ApiOperation(value = "导出票种列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:ticket:export')")
    @Log(title = "票种", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MyCyhTicket myCyhTicket) {
        List<MyCyhTicket> list = myCyhTicketService.selectMyCyhTicketList(myCyhTicket);
        ExcelUtil<MyCyhTicket> util = new ExcelUtil<MyCyhTicket>(MyCyhTicket.class);
        return util.exportExcel(list, "ticket");
    }

    /**
     * 获取票种详细信息
     */
    @ApiOperation(value = "获取票种详细信息",notes = "")
    @PreAuthorize("@ss.hasPermi('my:ticket:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(myCyhTicketService.selectMyCyhTicketById(id));
    }

    /**
     * 新增票种
     */
    @ApiOperation(value = "新增票种",notes = "")
    @PreAuthorize("@ss.hasPermi('my:ticket:add')")
    @Log(title = "票种", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MyCyhTicket myCyhTicket) {
        return toAjax(myCyhTicketService.insertMyCyhTicket(myCyhTicket));
    }

    /**
     * 修改票种
     */
    @ApiOperation(value = "修改票种",notes = "")
    @PreAuthorize("@ss.hasPermi('my:ticket:edit')")
    @Log(title = "票种", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MyCyhTicket myCyhTicket) {
        return toAjax(myCyhTicketService.updateMyCyhTicket(myCyhTicket));
    }

    /**
     * 删除票种
     */
    @ApiOperation(value = "删除票种",notes = "")
    @PreAuthorize("@ss.hasPermi('my:ticket:remove')")
    @Log(title = "票种", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(myCyhTicketService.deleteMyCyhTicketByIds(ids));
    }
}
